package cn.turboinfo.fuyang.api.gateway.mini.controller.file;

import cn.turboinfo.fuyang.api.domain.mini.usecase.file.MiniViewFileAttachmentUseCase;
import cn.turboinfo.fuyang.api.domain.web.usecase.file.UploadFileAttachmentUseCase;
import cn.turboinfo.fuyang.api.gateway.admin.framework.http.ResponseBodyWrapper;
import cn.turboinfo.fuyang.api.gateway.mini.fo.file.MiniFileUploadFO;
import cn.turboinfo.fuyang.api.gateway.mini.fo.file.MiniFileUploadResponse;
import cn.turboinfo.fuyang.api.gateway.mini.framework.http.MiniResponseBodyWrapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;

@Slf4j
@RequiredArgsConstructor
@Controller
@MiniResponseBodyWrapper
@RequestMapping("/mini/file")
public class MiniFileAttachmentController {

    private final UploadFileAttachmentUseCase uploadFileAttachmentUseCase;

    private final MiniViewFileAttachmentUseCase miniViewFileAttachmentUseCase;

    /**
     * 允许上传的附件类型
     */
    @Value("${kit.attachment.allowExt:}")
    private String allowExt;

    @PostMapping("/upload")
    @ResponseBodyWrapper
    public MiniFileUploadResponse upload(@Valid MiniFileUploadFO fo) {

        UploadFileAttachmentUseCase.OutputData outputData = uploadFileAttachmentUseCase.execute(UploadFileAttachmentUseCase
                .InputData
                .builder()
                .file(fo.getFile())
                .allowExts(StringUtils.split(allowExt, "|"))
                .relativePath(fo.getRelativePath())
                .refType(fo.getRefType())
                .refId(fo.getRefId())
                .build());

        return MiniFileUploadResponse
                .builder()
                .attachment(outputData.getAttachment())
                .build();
    }

    /**
     * 查看附件
     *
     * @param fileAttachmentId
     * @param response
     * @throws IOException
     */
    @GetMapping("/view/{fileAttachmentId}")
    public void view(@PathVariable Long fileAttachmentId, HttpServletResponse response) throws IOException {

        miniViewFileAttachmentUseCase.execute(MiniViewFileAttachmentUseCase.InputData
                .builder()
                .fileAttachmentId(fileAttachmentId)
                .response(response)
                .build());
    }

}
